package org.jeecg.modules.wlhy.yunfutong.service;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.SneakyThrows;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.entity.StringEntity;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.util.DateUtils;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.modules.third.ecloud.sdk.util.DateUtil;
import org.jeecg.modules.third.ecloud.sdk.util.MD5Util;
import org.jeecg.modules.third.openapi.WaybillRouteService;
import org.jeecg.modules.wlhy.bill.entity.HyShippingNoteBill;
import org.jeecg.modules.wlhy.captain.entity.HyCaptain;
import org.jeecg.modules.wlhy.captain.mapper.HyCaptainMapper;
import org.jeecg.modules.wlhy.company.entity.HyCompany;
import org.jeecg.modules.wlhy.company.entity.HyCompanyEtcConfig;
import org.jeecg.modules.wlhy.company.service.IHyCompanyEtcConfigService;
import org.jeecg.modules.wlhy.company.service.IHyCompanyService;
import org.jeecg.modules.wlhy.hyarea.mapper.HyAreaMapper;
import org.jeecg.modules.wlhy.hycarrier.entity.HyCarrier;
import org.jeecg.modules.wlhy.hydriver.entity.HyDriver;
import org.jeecg.modules.wlhy.hyvehicle.entity.HyVehicle;
import org.jeecg.modules.wlhy.shipping.dto.YunFuTongShippingNoteDTO;
import org.jeecg.modules.wlhy.shipping.entity.HyShippingNote;
import org.jeecg.modules.wlhy.shipping.entity.PointDataListVO;
import org.jeecg.modules.wlhy.shipping.entity.WaybillRouteVO;
import org.jeecg.modules.wlhy.shipping.mapper.HyShippingNoteMapper;
import org.jeecg.modules.wlhy.utils.HyCfgUtil;
import org.jeecg.modules.wlhy.yunfutong.entity.*;
import org.jeecg.modules.wlhy.yunfutong.mapper.OldWonerInfoMapper;
import org.jeecg.modules.wlhy.yunfutong.mapper.YsbShippingMapper;
import org.jeecg.modules.wlhy.yunfutong.req.CarConfirmInfo;
import org.jeecg.modules.wlhy.yunfutong.req.ConfirmInfo;
import org.jeecg.modules.wlhy.yunfutong.req.IsExist;
import org.jeecg.modules.wlhy.yunfutong.req.Waybill;
import org.jeecg.modules.wlhy.yunfutong.util.SM2Utils;
import org.jeecg.modules.wlhy.yunfutong.util.TestHttpClientUtil;
import org.jeecg.modules.wlhy.yunfutong.util.Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


@Service
@Log4j2
public class IhyYunfutongServiceAPI2 {

    @Value(value = "${ysb-daikai.baseUrl:}")
    private String baseUrl;

   /* @Value(value = "${ysb-daikai.username:}")
    private String username;

    @Value(value = "${ysb-daikai.password:}")
    private String password;
    @Value(value = "${ysb-daikai.reqUrl:}")
    private String reqUrl;
*/
    @Value(value = "${ysb-daikai.pubk:}")
    private String pubk;


    @Autowired
    private HyShippingNoteMapper hyShippingNoteMapper;

    @Autowired
    private YsbShippingMapper ysbShippingMapper;

    @Autowired
    private IHyCompanyService companyService;

    @Autowired
    private WaybillRouteService waybillRouteService;

    @Resource
    private HyCaptainMapper captainMapper;
    @Resource
    private OldWonerInfoMapper oldWonerInfoMapper;
    @Resource
    private HyAreaMapper areaMapper;

    @Autowired
    private IHyCompanyEtcConfigService companyEtcConfigService;

    @Resource
    RedisUtil redisUtil;

    //登录获取令牌
    //TODO 不能用静态，养成好习惯
    public Result<?> login(String companyId) {


        HyCompanyEtcConfig companyEtcConfig = companyEtcConfigService.getOne(new QueryWrapper<HyCompanyEtcConfig>().eq("company_id", companyId).eq("report_type",1000));
        if (companyEtcConfig == null) {
            return Result.error("未配置运服通配置信息");
        }
        String username = companyEtcConfig.getAccount();
        String password = companyEtcConfig.getPwd();
        JSONObject json = new JSONObject();
        json.put("account", username);
        json.put("password", MD5Util.encode(password));
        String url = companyEtcConfig.getEtcReportUrl()+"/api/v1/Auth/Login";
        HttpEntity entity;
        // 实体类转换为Map
        Map<String, String> map2 = JSON.parseObject(JSON.toJSONString(json), Map.class);
        entity = new StringEntity(JSONUtil.toJsonStr(map2), "utf-8");
        log.info("开始发送登录请求,请求参数为" + map2);
        String result = TestHttpClientUtil.httpPost(url, entity);
        log.info("发送登录请求完成，返回参数为" + result);
        JSONObject jsonObject = JSONObject.parseObject(result);
        if (jsonObject.getString("code").equals("-1")) {
            Result<?> reqResult = new Result<>();
            return reqResult.error500(jsonObject.get("msg").toString());
        }
        JSONObject data = jsonObject.getJSONObject("data");
        String token = data.getString("token");
        log.info("获取到token,token为" + token);
        return Result.OK(token);

    }

    /**
     * 上传司机照片
     *
     * @param driver
     * @param token
     * @return
     */
    public HyDriver uploadDriver(HyDriver driver, String token,String companyId) {

        String idcardImg = upload(driver.getIdcardImg(), token, "0",companyId);
        String IdcardImgBack = upload(driver.getIdcardImgBack(), token, "0",companyId);
        String driverImg = upload(driver.getDriverImg(), token, "0",companyId);
        String driverImg2 = upload((driver.getDriverImg2()), token, "0",companyId);
        String qualificationImg = upload(driver.getQualificationImg(), token, "0",companyId);
        driver.setIdcardImg(idcardImg);
        driver.setIdcardImgBack(IdcardImgBack);
        driver.setDriverImg(driverImg);
        driver.setDriverImg2(driverImg2);
        driver.setQualificationImg(qualificationImg);


        return driver;


    }


    /**
     * 导入司机
     *
     * @param driver
     * @param token
     * @param req
     * @param vehicle
     * @return
     */
    public Result<?> importDriver(HyDriver driver, String token, HttpServletRequest req, HyVehicle vehicle,String companyId) {

        if (driver != null) {
            //业务数据
            YunfutongDriver yunfutongDriver = new YunfutongDriver();
            yunfutongDriver.setTelPhone(driver.getTelephone());
            yunfutongDriver.setDriverName(driver.getDriverName());
            //yunfutongDriverSex:0男1女
            if (StringUtils.isNotEmpty(driver.getSex())){
                if (driver.getSex().equals("1")) {
                    yunfutongDriver.setDriverSex("0");
                } else {
                    yunfutongDriver.setDriverSex("1");
                }
            }


            yunfutongDriver.setDriverIDCard(driver.getIdcard());
            yunfutongDriver.setDriverLicenseType(driver.getVehicleClass());
            yunfutongDriver.setRtqCertificate(driver.getQualificationCertificate());
            yunfutongDriver.setDriverLicenseDateStart(DateUtil.fomatString2(driver.getValidPeriodFrom()));
            yunfutongDriver.setDriverLicenseDateEnd(DateUtil.fomatString2(driver.getValidPeriodTo()));
            yunfutongDriver.setDriverLicesenAuthority(driver.getIssuingOrganizations());
            yunfutongDriver.setVehicleCarNumber(vehicle.getVehicleNumber());
            yunfutongDriver.setIdentityType("1");

            ConfirmInfo confirmInfo = new ConfirmInfo();
            confirmInfo.setTelPhone(driver.getTelephone());
            confirmInfo.setDriverCardOnURL(driver.getIdcardImg());
            confirmInfo.setDriverCardBackURL(driver.getIdcardImgBack());
            confirmInfo.setDriverLicenseOnURL(driver.getDriverImg());
            confirmInfo.setDriverLicenseBackURL(driver.getDriverImg2());
            confirmInfo.setRtqCertificateURL(driver.getQualificationImg());
            yunfutongDriver.setConfirmInfo(confirmInfo);

            HyCompanyEtcConfig companyEtcConfig = companyEtcConfigService.getOne(new QueryWrapper<HyCompanyEtcConfig>().eq("company_id",companyId).eq("report_type",1000));
            //请求数据
            String addDriverUrl = companyEtcConfig.getEtcReportUrl()+"/api/v2/Driver/Import";

            //生成16位随机密钥
            String key = UUID.randomUUID().toString().replaceAll("-", "").substring(0, 16);
            byte[] keyByte = key.getBytes();
            log.info(key);
            //平台账号下对应公钥
          //  String pubk = "0404B2D01C149800E3961676191F9763D02347E6E2B490615D2FD83082F78C20220570F9AFE317D317E1DA9CF1DD5DF7BB4D750FC3DED2A20DD7775930569DF60D";
            log.info("SM2加密输出 encryptCode: ");
            String encryptCode = null;
            String result = null;
            JSONObject jsonObject = null;
            try {
                encryptCode = SM2Utils.encrypt(Util.hexToByte(pubk), keyByte);
                log.info(encryptCode);

                String encryptData = JSONUtil.toJsonStr(yunfutongDriver);
                log.info(encryptData);
                log.info("");

                log.info("最终用postman提交的Json数据包");
                JSONObject postJson = new JSONObject();
                postJson.put("reqTime", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
                postJson.put("token", token);
                postJson.put("encryptCode", encryptCode);
                postJson.put("encryptData", encryptData);
                log.info("最终postman提交的数据为" + postJson.toString());
                HttpEntity entity;
                // 实体类转换为Map
                Map<String, String> map2 = JSON.parseObject(JSON.toJSONString(postJson), Map.class);
                log.info("开始发送添加司机请求,请求参数为" + map2);
                entity = new StringEntity(JSONUtil.toJsonStr(map2), "utf-8");
                result = TestHttpClientUtil.httpPost(addDriverUrl, entity);
                log.info(result.toString());
                jsonObject = JSONObject.parseObject(result);
                if (jsonObject.getString("code").equals("-1")) {
                    return Result.error(jsonObject.get("msg").toString());
                }


            } catch (IOException e) {
                e.printStackTrace();
            }

        }
        return Result.OK();
    }

    /**
     * 新增司机到草稿箱
     * @param driver
     * @param token
     * @param req
     * @param vehicle
     * @return
     */
    public Result<?> addDriver(HyDriver driver, String token, HttpServletRequest req, HyVehicle vehicle, String companyId) {

        if (driver != null) {
            //业务数据
            YunfutongDriver yunfutongDriver = new YunfutongDriver();
            yunfutongDriver.setTelPhone(driver.getTelephone());
            yunfutongDriver.setDriverName(driver.getDriverName());
            //yunfutongDriverSex:0男1女
            if (StringUtils.isNotEmpty(driver.getSex())){
                if (driver.getSex().equals("1")) {
                    yunfutongDriver.setDriverSex("0");
                } else {
                    yunfutongDriver.setDriverSex("1");
                }
            }


            yunfutongDriver.setDriverIDCard(driver.getIdcard());
            yunfutongDriver.setDriverLicenseType(driver.getVehicleClass());
            yunfutongDriver.setRtqCertificate(driver.getQualificationCertificate());
            yunfutongDriver.setDriverLicenseDateStart(DateUtil.fomatString2(driver.getValidPeriodFrom()));
            yunfutongDriver.setDriverLicenseDateEnd(DateUtil.fomatString2(driver.getValidPeriodTo()));
            yunfutongDriver.setDriverLicesenAuthority(driver.getIssuingOrganizations());
            yunfutongDriver.setVehicleCarNumber(vehicle.getVehicleNumber());
            yunfutongDriver.setIdentityType("1");

            ConfirmInfo confirmInfo = new ConfirmInfo();
            confirmInfo.setTelPhone(driver.getTelephone());
            confirmInfo.setDriverCardOnURL(driver.getIdcardImg());
            confirmInfo.setDriverCardBackURL(driver.getIdcardImgBack());
            confirmInfo.setDriverLicenseOnURL(driver.getDriverImg());
            confirmInfo.setDriverLicenseBackURL(driver.getDriverImg2());
            confirmInfo.setRtqCertificateURL(driver.getQualificationImg());
            yunfutongDriver.setConfirmInfo(confirmInfo);

            //请求数据
            HyCompanyEtcConfig companyEtcConfig = companyEtcConfigService.getOne(new QueryWrapper<HyCompanyEtcConfig>().eq("company_id", companyId).eq("report_type",1000));
            String addDriverUrl = companyEtcConfig.getEtcReportUrl()+"/api/v1/Driver/Add";

            //生成16位随机密钥
            String key = UUID.randomUUID().toString().replaceAll("-", "").substring(0, 16);
            byte[] keyByte = key.getBytes();
            log.info(key);
            //平台账号下对应公钥
            //  String pubk = "0404B2D01C149800E3961676191F9763D02347E6E2B490615D2FD83082F78C20220570F9AFE317D317E1DA9CF1DD5DF7BB4D750FC3DED2A20DD7775930569DF60D";
            log.info("SM2加密输出 encryptCode: ");
            String encryptCode = null;
            String result = null;
            JSONObject jsonObject = null;
            try {
                encryptCode = SM2Utils.encrypt(Util.hexToByte(pubk), keyByte);
                log.info(encryptCode);

                String encryptData = JSONUtil.toJsonStr(yunfutongDriver);
                log.info(encryptData);
                log.info("");

                log.info("最终用postman提交的Json数据包");
                JSONObject postJson = new JSONObject();
                postJson.put("reqTime", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
                postJson.put("token", token);
                postJson.put("encryptCode", encryptCode);
                postJson.put("encryptData", encryptData);
                log.info("最终postman提交的数据为" + postJson.toString());
                HttpEntity entity;
                // 实体类转换为Map
                Map<String, String> map2 = JSON.parseObject(JSON.toJSONString(postJson), Map.class);
                log.info("开始发送添加司机请求,请求参数为" + map2);
                entity = new StringEntity(JSONUtil.toJsonStr(map2), "utf-8");
                result = TestHttpClientUtil.httpPost(addDriverUrl, entity);
                log.info(result.toString());
                jsonObject = JSONObject.parseObject(result);
                if (jsonObject.getString("code").equals("-1")) {
                    return Result.error(jsonObject.get("msg").toString());
                }


            } catch (IOException e) {
                e.printStackTrace();
            }

        }
        return Result.OK();
    }
    /**
     * 上传车辆照片
     *
     * @param vehicle
     * @param token
     * @return
     */
    public HyVehicle uploadVehicle(HyVehicle vehicle, String token, String companyId) {

        String drivingLicenseImg = upload(vehicle.getDrivingLicenseImg(), token, "1", companyId);
        String drivingLicenseImg2 = upload(vehicle.getDrivingLicenseImg2(), token, "1",companyId);
        String roadTransportImg = upload(vehicle.getRoadTransportImg(), token, "1",companyId);

        vehicle.setDrivingLicenseImg(drivingLicenseImg);
        vehicle.setDrivingLicenseImg2(drivingLicenseImg2);
        vehicle.setRoadTransportImg(roadTransportImg);
        return vehicle;

    }

    //添加车辆
    public Result<?> addVehicle(HyVehicle vehicle, HyDriver driver, String token,String companyId) {

        YsbVehicle ysbVehicle = new YsbVehicle();
        if (vehicle != null) {
            //业务代码
            ysbVehicle.setVehicleCarNumber(vehicle.getVehicleNumber());
            ysbVehicle.setCarNumberColor(vehicle.getVehiclePlateColorCode());
            ysbVehicle.setVehiclePowerType(vehicle.getVehicleEnergyType());
            ysbVehicle.setVehicleMaster(vehicle.getOwner());
            ysbVehicle.setVehicleLoad(vehicle.getVehicleTonnage());
            ysbVehicle.setVehicleLoadWeight(vehicle.getGrossMass());
            ysbVehicle.setVehicleLength(new BigDecimal(vehicle.getVehicleLong()));
            ysbVehicle.setVehicleTypeName(vehicle.getVehicleType());

            CarConfirmInfo carConfirmInfo = new CarConfirmInfo();
            carConfirmInfo.setVehicleLicenseFrontPageURL(vehicle.getDrivingLicenseImg());
            carConfirmInfo.setVehicleLicenseSubPageOnURL(vehicle.getDrivingLicenseImg2());
            carConfirmInfo.setVehicleRTPUTL(vehicle.getRoadTransportImg());
            ysbVehicle.setCarConfirmInfo(carConfirmInfo);

            //请求数据
            HyCompanyEtcConfig companyEtcConfig = companyEtcConfigService.getOne(new QueryWrapper<HyCompanyEtcConfig>().eq("company_id", companyId).eq("report_type",1000));
            String addDriverUrl = companyEtcConfig.getEtcReportUrl()+"/api/v2/Car/Add";

            //生成16位随机密钥
            String key = UUID.randomUUID().toString().replaceAll("-", "").substring(0, 16);
            byte[] keyByte = key.getBytes();
            log.info(key);
            //平台账号下对应公钥
           // String pubk = "0404B2D01C149800E3961676191F9763D02347E6E2B490615D2FD83082F78C20220570F9AFE317D317E1DA9CF1DD5DF7BB4D750FC3DED2A20DD7775930569DF60D";
            log.info("SM2加密输出 encryptCode: ");
            String encryptCode = null;
            String result = null;
            JSONObject jsonObject = null;
            try {
                encryptCode = SM2Utils.encrypt(Util.hexToByte(pubk), keyByte);
                log.info(encryptCode);

                String encryptData = JSONUtil.toJsonStr(ysbVehicle);
                log.info(encryptData);
                log.info("");

                log.info("最终用postman提交的Json数据包");
                JSONObject postJson = new JSONObject();
                postJson.put("reqTime", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
                postJson.put("token", token);
                postJson.put("encryptCode", encryptCode);
                postJson.put("encryptData", encryptData);
                log.info("最终postman提交的数据为" + postJson.toString());
                HttpEntity entity;
                // 实体类转换为Map
                Map<String, String> map2 = JSON.parseObject(JSON.toJSONString(postJson), Map.class);
                log.info("开始发送添加车辆请求,请求参数为" + map2);
                entity = new StringEntity(JSONUtil.toJsonStr(map2), "utf-8");
                result = TestHttpClientUtil.httpPost(addDriverUrl, entity);
                log.info(result.toString());
                jsonObject = JSONObject.parseObject(result);
                if (jsonObject.getString("code").equals("-1")) {
                    return Result.error(jsonObject.get("msg").toString());
                }


            } catch (IOException e) {
                e.printStackTrace();
            }

        }
        return Result.OK();


    }

    @SneakyThrows
    public boolean IsExist(String driverIdcard, String token, String vehicleNumber,String companyId) {
        log.info("开始检查司机是否存在货主名下");
        //请求数据
       HyCompanyEtcConfig companyEtcConfig = companyEtcConfigService.getOne(new QueryWrapper<HyCompanyEtcConfig>().eq("company_id", companyId).eq("report_type",1000));
        String reqUrl = companyEtcConfig.getEtcReportUrl();
        String driverUrl = reqUrl+"/api/v1/Driver/IsExist";
        String vehicleurl = reqUrl+"/api/v1/Car/IsExist";
        String url;
        IsExist exist = new IsExist();
        if (driverIdcard != null) {
            if (redisUtil.hasKey(driverIdcard)) {
                return true;
            }
            url = driverUrl;
            exist.setIdCard(driverIdcard);
        } else {
            if (redisUtil.hasKey(vehicleNumber)) {
                return true;
            }
            url = vehicleurl;
            exist.setCarNumber(vehicleNumber);
        }

        //生成16位随机密钥
        String key = UUID.randomUUID().toString().replaceAll("-", "").substring(0, 16);
        byte[] keyByte = key.getBytes();
        log.info(key);
        //平台账号下对应公钥
        //String pubk = "0404B2D01C149800E3961676191F9763D02347E6E2B490615D2FD83082F78C20220570F9AFE317D317E1DA9CF1DD5DF7BB4D750FC3DED2A20DD7775930569DF60D";
        log.info("SM2加密输出 encryptCode: ");
        String encryptCode = null;
        String result = null;
        JSONObject jsonObject = null;
        try {
            encryptCode = SM2Utils.encrypt(Util.hexToByte(pubk), keyByte);
            log.info(encryptCode);

            String encryptData = JSONUtil.toJsonStr(exist);
            log.info(encryptData);
            log.info("");

            log.info("最终用postman提交的Json数据包");
            JSONObject postJson = new JSONObject();
            postJson.put("reqTime", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
            postJson.put("token", token);
            postJson.put("encryptCode", encryptCode);
            postJson.put("encryptData", encryptData);
            log.info("最终postman提交的数据为" + postJson.toString());
            HttpEntity entity;
            // 实体类转换为Map
            Map<String, String> map2 = JSON.parseObject(JSON.toJSONString(postJson), Map.class);
            log.info("开始发送查看司机是否存在请求,请求参数为" + map2);
            entity = new StringEntity(JSONUtil.toJsonStr(map2), "utf-8");
            result = TestHttpClientUtil.httpPost(url, entity);
            log.info(result.toString());
            jsonObject = JSONObject.parseObject(result);
            if (jsonObject.getString("code").equals("-1")) {
                return false;
            }

        } catch (IOException e) {
            e.printStackTrace();
        }

        JSONObject data = jsonObject.getJSONObject("data");
        log.info(data.toString());
        Boolean isAny = Boolean.parseBoolean(data.getString("isAny"));
        log.info(isAny);
        if (isAny) {
            //存入redis缓存中
            redisUtil.set(driverIdcard,"1", 24*60*60);
        }
        return isAny;

    }
    public Result<?> checkDriver(String driverIdcard, String token,String phone,String companyId) {

        log.info("开始检查司机是否存在系统种");
        //请求数据
       HyCompanyEtcConfig companyEtcConfig = companyEtcConfigService.getOne(new QueryWrapper<HyCompanyEtcConfig>().eq("company_id", companyId).eq("report_type",1000));
        String reqUrl = companyEtcConfig.getEtcReportUrl();
        String driverUrl = reqUrl+"/api/v2/Driver/Check";
        IsExist exist = new IsExist();
        String url = driverUrl;
        exist.setIdCard(driverIdcard);
        exist.setPhone(phone);


        //生成16位随机密钥
        String key = UUID.randomUUID().toString().replaceAll("-", "").substring(0, 16);
        byte[] keyByte = key.getBytes();
        log.info(key);
        //平台账号下对应公钥
        //String pubk = "0404B2D01C149800E3961676191F9763D02347E6E2B490615D2FD83082F78C20220570F9AFE317D317E1DA9CF1DD5DF7BB4D750FC3DED2A20DD7775930569DF60D";
        log.info("SM2加密输出 encryptCode: ");
        String encryptCode = null;
        String result = null;
        JSONObject jsonObject = null;
        try {
            encryptCode = SM2Utils.encrypt(Util.hexToByte(pubk), keyByte);
            log.info(encryptCode);

            String encryptData = JSONUtil.toJsonStr(exist);
            log.info(encryptData);
            log.info("");

            log.info("最终用postman提交的Json数据包");
            JSONObject postJson = new JSONObject();
            postJson.put("reqTime", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
            postJson.put("token", token);
            postJson.put("encryptCode", encryptCode);
            postJson.put("encryptData", encryptData);
            log.info("最终postman提交的数据为" + postJson.toString());
            HttpEntity entity;
            // 实体类转换为Map
            Map<String, String> map2 = JSON.parseObject(JSON.toJSONString(postJson), Map.class);
            log.info("开始发送查看司机是否存在请求,请求参数为" + map2);
            entity = new StringEntity(JSONUtil.toJsonStr(map2), "utf-8");
            result = TestHttpClientUtil.httpPost(url, entity);
            log.info(result.toString());
            jsonObject = JSONObject.parseObject(result);
            if (jsonObject.getString("code").equals("-1")) {
                return Result.error(jsonObject.get("msg").toString());
            }

        } catch (IOException e) {
            log.error("查看司机是否存在失败"+"原因是"+e.getMessage());
            return Result.error("查看司机是否存在失败");
        }

        JSONObject data = jsonObject.getJSONObject("data");
        log.info("获取检查司机的结果为==="+data.toString());
       Integer status = Integer.valueOf(data.getString("status"));
       log.info("status==="+status);
       if (status!=0){
           log.info("司机不合法");
           return Result.error(data.getString("msg"));
       }
       return Result.OK();
    }

    /**
     * 添加运单
     *
     * @param shippingNote
     * @param driver
     * @param vehicle
     * @param token
     * @param shippingNoteBill
     * @return
     */
    public Result<?> addShippingNote(HyShippingNote shippingNote, HyDriver driver, HyVehicle vehicle, String token, HyShippingNoteBill shippingNoteBill, HyCarrier hyCarrier) {
        if (shippingNote != null) {

            //业务数据
            ysbWaybill ysbWaybill = new ysbWaybill();
            Waybill waybill = new Waybill();
            ysbWaybill.setFileName("正式业务");
            ysbWaybill.setTaskType("02");//业务类型
            ysbWaybill.setTaskSceneType("3");//业务场景类型
            ysbWaybill.setInvoiceType("02");//发票类型

            waybill.setCarriageBillID(shippingNote.getShippingNoteNumber());
            waybill.setTaskType("02");
            log.info("hippingNote.getCompanyId===="+shippingNote.getCompanyId());
            HyCompany company = companyService.getById(shippingNote.getCompanyId());
            if (company==null){
                return Result.error("分公司不存在");
            }
            String companyName = company.getCompanyName();
            waybill.setGoodsOwnerName(companyName);//货主名称
            waybill.setDriverName(driver.getDriverName());
            waybill.setDriverPhone(driver.getTelephone());
            waybill.setDriverIDCard(driver.getIdcard());
            if (shippingNote.getTosIdentification().equals("1")){
                log.info("共创原系统旧数据上报");
                if (shippingNoteBill.getCarrier().equals(driver.getDriverName())){
                    waybill.setPayeeName(driver.getDriverName());
                    waybill.setPayeePhone(driver.getTelephone());
                    waybill.setPayeeIDCard(driver.getIdcard());
                }else {
                    waybill.setPayeeName(shippingNoteBill.getCarrier());
                    //通过名字获取手机号
                    String phone = oldWonerInfoMapper.selectOne(new LambdaQueryWrapper<OldWonerInfo>().eq(OldWonerInfo::getName,shippingNoteBill.getCarrier())).getPhone();
                    waybill.setPayeePhone(phone);
                    waybill.setPayeeIDCard(shippingNoteBill.getActualCarrierId());
                    waybill.setLeaderName(shippingNoteBill.getCarrier());
                    waybill.setLeaderIDCard(shippingNoteBill.getActualCarrierId());
                    waybill.setLeaderPhone(phone);
                }


            }else {
                //如果是车队长模式的话，收款人信息为车队长信息
                if (shippingNote.getPayType().equals("2")) {
                    log.info("代收人信息======{}{}{}{}"+hyCarrier.getCarrierName()+hyCarrier.getTel()+hyCarrier.getIdcard());
                    waybill.setPayeeName(hyCarrier.getCarrierName());
                    waybill.setPayeePhone(hyCarrier.getTel());
                    waybill.setPayeeIDCard(hyCarrier.getIdcard());
                    waybill.setLeaderName(hyCarrier.getCarrierName());
                    waybill.setLeaderIDCard(hyCarrier.getIdcard());
                    waybill.setLeaderPhone(hyCarrier.getTel());
                    log.info("发送的收款人信息==="+waybill.getPayeeName()+waybill.getPayeePhone()+waybill.getPayeeIDCard());
                }else if (shippingNote.getIzCaptainShipping().equals("1")){
                    //承运商模式
                    HyCaptain captain = captainMapper.selectById(shippingNote.getCaptainId());
                    waybill.setPayeeName(captain.getCaptainName());
                    waybill.setPayeePhone(captain.getKhTel());//
                    waybill.setPayeeIDCard(captain.getIdcard());
                    waybill.setLeaderName(captain.getCaptainName());
                    waybill.setLeaderIDCard(captain.getIdcard());
                    waybill.setLeaderPhone(captain.getKhTel());
                }else {
                    waybill.setPayeeName(driver.getDriverName());
                    waybill.setPayeePhone(driver.getTelephone());
                    waybill.setPayeeIDCard(driver.getIdcard());
                }
            }

            waybill.setCarNumber(vehicle.getVehicleNumber());
            waybill.setLoadNetWeight(shippingNote.getGoodsWeightLoading());
            waybill.setGoodsName(shippingNote.getDescriptionOfGoods());//货品名称
            //进行单位转换
            if (shippingNote.getGoodsUnit().equals("1")) {
                waybill.setGoodsUnit("04");
            } else if (shippingNote.getGoodsUnit().equals("2")) {
                waybill.setGoodsUnit("02");
            } else {
                waybill.setGoodsUnit("10");
            }
            waybill.setLoadingDatetime(DateUtil.fomatString(shippingNote.getStatusDtLoading()));
            waybill.setSignDatetime(DateUtil.fomatString(shippingNote.getStatusDtUnloading()));//装车时间


           /* waybill.setDriverCarryPrice(shippingNote.getShippingUnitPrice());//司机运输单价
            waybill.setCarriageTotalPrice(shippingNote.getDriverFee());//运费*/
            //如果是老系统的数据的话，委托代开费用直接为司机运费
            if (shippingNote.getTosIdentification().equals("1")){
                //司机运费单价=司机运费/司机装货数量
                BigDecimal ShippingUnitPrice=  shippingNoteBill.getAmt().divide(shippingNote.getGoodsWeightUnloading(),2,BigDecimal.ROUND_HALF_UP);
                waybill.setDriverAllotCount(shippingNote.getGoodsWeightUnloading());//司机卸货数量
                waybill.setEntrustedCollectionAmount(shippingNoteBill.getAmt());//委托代开金额
                waybill.setDriverCarryPrice(ShippingUnitPrice);//司机运输单价
                //运费=单价*数量
                waybill.setCarriageTotalPrice(shippingNoteBill.getAmt());//运费
                //获取运单的所属货主发货地址的areaCode
              //  String sendAreaCode = hyCustomerAddressSendMapper.selectOne(new LambdaQueryWrapper<HyCustomerAddressSend>().eq(HyCustomerAddressSend::getCustomerId,shippingNote.getSend)).getAreaCode();
              //  String receiveCode = hyCustomerAddressReceiveMapper.selectOne(new LambdaQueryWrapper<HyCustomerAddressReceive>().eq(HyCustomerAddressReceive::getCustomerId,shippingNote.getCustomerId())).getAreaCode();
                //获取省市区三级名称
                addressDTO sendAddressDTO = areaMapper.getAreaName(shippingNote.getSendAreaCode());
                addressDTO receiveAddressDTO = areaMapper.getAreaName(shippingNote.getReceiveAreaCode());
                waybill.setOriginAddress(sendAddressDTO.getProvinceName()+sendAddressDTO.getCityName()+sendAddressDTO.getAreaName()+shippingNote.getSendAddress());
                waybill.setArriveAddress(receiveAddressDTO.getProvinceName()+receiveAddressDTO.getCityName()+receiveAddressDTO.getAreaName()+shippingNote.getReceiveAddress());
            }else {
                /*//如果使用油气的话委托代开费用就是总运费-油气费
                if (!shippingNote.getIzUsedGas().equals("0")){
                    waybill.setEntrustedCollectionAmount(shippingNoteBill.getAmt().subtract(shippingNote.getGasRechargeAmount()));//委托代开运费
                }else {
                    waybill.setEntrustedCollectionAmount(shippingNote.getDriverFee());
                }*/
                waybill.setEntrustedCollectionAmount(shippingNoteBill.getAmt());//委托代开金额
                //如果是包车价的话，司机装货量改为1
                if (shippingNote.getShippingType().equals("4")){
                    waybill.setDriverAllotCount(new BigDecimal("1.00"));
                    waybill.setDriverCarryPrice(shippingNote.getShippingUnitPrice());//司机运输单价
                    waybill.setCarriageTotalPrice(shippingNote.getShippingUnitPrice());//运费
                }else {
                    waybill.setDriverAllotCount(shippingNote.getGoodsWeightUnloading());//司机装货数量
                    waybill.setDriverCarryPrice(shippingNote.getShippingUnitPrice());//司机运输单价
                    waybill.setCarriageTotalPrice(shippingNote.getShippingUnitPrice().multiply(shippingNote.getGoodsWeightUnloading()));//运费
                }
                waybill.setOriginAddress(shippingNote.getSendAddress());
                waybill.setArriveAddress(shippingNote.getReceiveAddress());
            }
            if (StringUtils.isEmpty(shippingNoteBill.getBankHdImg())&&StringUtils.isEmpty(shippingNoteBill.getBankHd())){
                return Result.error("请上传电子回单图片");
            }else {
                if (StringUtils.isNotEmpty(shippingNoteBill.getBankHdImg())) {
                    log.info("电子回单图片");
                    waybill.setBankReceiptUrl(shippingNoteBill.getBankHdImg());
                } else {
                    log.info("电子回单");
                    waybill.setBankReceiptUrl(shippingNoteBill.getBankHd());
                }
            }

            if (StringUtils.isNotEmpty(shippingNote.getShippingContract())){
                waybill.setContractUrl(shippingNote.getShippingContract());
            }
            List<String> TransportUrlList = new ArrayList<>();
            if (StringUtils.isNotEmpty(shippingNote.getImgLoading())){
                TransportUrlList.add(shippingNote.getImgLoading());
            }
            if (StringUtils.isNotEmpty(shippingNote.getImgUnloading())){
                TransportUrlList.add(shippingNote.getImgUnloading());
            }
            if (StringUtils.isNotEmpty(shippingNote.getLoadingSceneImg())){
                TransportUrlList.add(shippingNote.getLoadingSceneImg());
            }
            if (StringUtils.isNotEmpty(shippingNote.getUnloadingSceneImg())){
                TransportUrlList.add(shippingNote.getUnloadingSceneImg());
            }
            waybill.setTransportUrlList(TransportUrlList);
            List<Object> waybills = new ArrayList<>();
            waybills.add(waybill);
            ysbWaybill.setWaybills(waybills);



            //请求数据
            HyCompanyEtcConfig companyEtcConfig = companyEtcConfigService.getOne(new QueryWrapper<HyCompanyEtcConfig>().eq("company_id", shippingNote.getCompanyId()).eq("report_type",1000));
            String addshippingNoteUrl = companyEtcConfig.getEtcReportUrl()+"/api/v1/Waybill/UploadWaybill";

            //生成16位随机密钥
          //  String key = UUID.randomUUID().toString().replaceAll("-", "").substring(0, 16);
          //  byte[] keyByte = key.getBytes();
           // log.info(key);
            //平台账号下对应公钥
            //String pubk = "0404B2D01C149800E3961676191F9763D02347E6E2B490615D2FD83082F78C20220570F9AFE317D317E1DA9CF1DD5DF7BB4D750FC3DED2A20DD7775930569DF60D";
          //  log.info("SM2加密输出 encryptCode: ");
           // String encryptCode = null;
            String result = null;
            JSONObject jsonObject = null;

             //   encryptCode = SM2Utils.encrypt(Util.hexToByte(pubk), keyByte);
           //     log.info(encryptCode);

                String encryptData = JSONUtil.toJsonStr(ysbWaybill);
                log.info(encryptData);
                log.info("");

                log.info("最终用postman提交的Json数据包");
                JSONObject postJson = new JSONObject();
                postJson.put("reqTime", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
                postJson.put("token", token);
                postJson.put("encryptCode", "");
                postJson.put("encryptData", encryptData);
             //   log.info("最终postman提交的数据为" + postJson.toString());
                HttpEntity entity;
                // 实体类转换为Map
                Map<String, String> map2 = JSON.parseObject(JSON.toJSONString(postJson), Map.class);
                log.info("开始发送添加运单请求");
                entity = new StringEntity(JSONUtil.toJsonStr(map2), "utf-8");
                result = TestHttpClientUtil.httpPost(addshippingNoteUrl, entity);
                log.info("添加运单完成，返回结果是"+result.toString());
                jsonObject = JSONObject.parseObject(result);
                if (jsonObject.getString("code").equals("-1")) {
                    return Result.error(jsonObject.get("msg").toString());
                }

                JSONObject data = jsonObject.getJSONObject("data");
                String importBatchId = data.getString("importBatchID");
                YsbShipping ysbShipping = new YsbShipping();
                ysbShipping.setShippingId(shippingNote.getId());
                ysbShipping.setImportBatchId(importBatchId);
                ysbShippingMapper.insert(ysbShipping);

        } else {
            return Result.error("数据为空");
        }
        return Result.OK();
    }

    /**
     * 运单凭证上传
     *
     * @param token
     * @param shippingNote
     * @return
     */
    public HyShippingNote shippingNoteUpload(String token, HyShippingNote shippingNote) {
        log.info("开始运单凭证上传");

       /* ExecutorService executorService = Executors.newFixedThreadPool(5); // 创建一个固定大小的线程池
        List<Future<String>> futures = new ArrayList<>();

        // 提交任务到线程池
        futures.add(executorService.submit(() -> uploadImage(shippingNote.getImgLoading(), token, "装货凭证")));
        futures.add(executorService.submit(() -> uploadImage(shippingNote.getImgUnloading(), token, "卸货凭证")));
        futures.add(executorService.submit(() -> uploadImage(shippingNote.getLoadingSceneImg(), token, "装货现场照片")));
        futures.add(executorService.submit(() -> uploadImage(shippingNote.getUnloadingSceneImg(), token, "卸货现场照片")));

        // 处理上传结果
        try {
            shippingNote.setImgLoading(futures.get(0).get());
            shippingNote.setImgUnloading(futures.get(1).get());
            shippingNote.setLoadingSceneImg(futures.get(2).get());
            shippingNote.setUnloadingSceneImg(futures.get(3).get());
        } catch (InterruptedException | ExecutionException e) {
            log.error("文件上传失败", e);
            Thread.currentThread().interrupt();
        }
        executorService.shutdown(); // 关闭线程池*/
        shippingNote.setImgLoading(uploadImage(shippingNote.getImgLoading(), token, "装货凭证",shippingNote.getCompanyId()));
        shippingNote.setImgUnloading(uploadImage(shippingNote.getImgUnloading(), token, "卸货凭证",shippingNote.getCompanyId()));
        shippingNote.setLoadingSceneImg(uploadImage(shippingNote.getLoadingSceneImg(), token, "装货现场照片",shippingNote.getCompanyId()));
        shippingNote.setUnloadingSceneImg(uploadImage(shippingNote.getUnloadingSceneImg(), token, "卸货现场照片",shippingNote.getCompanyId()));
        // 上传合同
        if (StringUtils.isNotEmpty(shippingNote.getShippingContract())) {
            try {
                String shippingContract = upload(shippingNote.getShippingContract(), token, "2",shippingNote.getCompanyId());
                log.info("合同地址===={}", shippingContract);
                shippingNote.setShippingContract(shippingContract);
            } catch (Exception e) {
                log.error("合同上传失败", e);
            }
        }
        return shippingNote;
    }

    private String uploadImage(String url, String token, String logMessage,String companyId) {
        if (StringUtils.isNotEmpty(url)) {
            try {
                String uploadedUrl = shippingnoteForUtil(url, token,companyId);
                log.info("{}===={}", logMessage, uploadedUrl);
                return uploadedUrl;
            } catch (Exception e) {
                log.error("{}上传失败", logMessage, e);
            }
        }
        return url;
    }

    /**
     * 上传银行回单凭证
     *
     * @param token
     * @param shippingNoteBill
     * @return
     */
    public HyShippingNoteBill ShippingNoteBillUpload(String token, HyShippingNoteBill shippingNoteBill) {

        if (shippingNoteBill.getBankHdImg() != null) {
            String bankHdImg = upload(shippingNoteBill.getBankHdImg(), token, "2",shippingNoteBill.getCompanyId());
            shippingNoteBill.setBankHdImg(bankHdImg);
        }else {
            if (shippingNoteBill.getBankHd() != null) {
                String bankHd = upload(shippingNoteBill.getBankHd(), token, "2",shippingNoteBill.getCompanyId());
                shippingNoteBill.setBankHd(bankHd);
            }
        }


        return shippingNoteBill;
    }
    /**
     * 上传
     * @param url
     * @param token
     * @param fileType
     * @return
     */
    @SneakyThrows
    private String upload(String url, String token, String fileType,String companyId) {

        //请求数据
        HyCompanyEtcConfig companyEtcConfig = companyEtcConfigService.getOne(new QueryWrapper<HyCompanyEtcConfig>().eq("company_id", companyId).eq("report_type",1000));
        String uploadUrl = companyEtcConfig.getEtcReportUrl()+"/api/v1/File/UploadFile";

        //生成16位随机密钥
        String key = UUID.randomUUID().toString().replaceAll("-", "").substring(0, 16);
        byte[] keyByte = key.getBytes();
        log.info(key);
        //平台账号下对应公钥
      //  String pubk = "0404B2D01C149800E3961676191F9763D02347E6E2B490615D2FD83082F78C20220570F9AFE317D317E1DA9CF1DD5DF7BB4D750FC3DED2A20DD7775930569DF60D";
       // log.info("SM2加密输出 encryptCode: ");
        String encryptCode = null;
        String result = null;
        JSONObject jsonObject = null;
        try {
           // encryptCode = SM2Utils.encrypt(Util.hexToByte(pubk), keyByte);
            //log.info(encryptCode);

            String fileUrl = this.baseUrl + "/sys/common/static/" + encode(url, "UTF-8");

            //创建json实体
            JSONObject json = new JSONObject();
            json.put("fileUrl", fileUrl);
            json.put("fileBase64", "");
            json.put("fileType", fileType);


            String encryptData = JSONUtil.toJsonStr(json);
            log.info(encryptData);


            log.info("最终用postman提交的Json数据包");
            JSONObject postJson = new JSONObject();
            postJson.put("reqTime", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
            postJson.put("token", token);
            postJson.put("encryptCode", "");
            postJson.put("encryptData", encryptData);

            HttpEntity entity;
            // 实体类转换为Map
            Map<String, String> map2 = JSON.parseObject(JSON.toJSONString(postJson), Map.class);
            log.info("开始发送上传请求,请求参数为" + map2);
            entity = new StringEntity(JSONUtil.toJsonStr(map2), "utf-8");
            result = TestHttpClientUtil.httpPost(uploadUrl, entity);
            log.info("返回的结果是==="+result.toString());
            jsonObject = JSONObject.parseObject(result);
            if (jsonObject.getString("code").equals("-1")) {
                throw new Exception(jsonObject.get("msg").toString());
            }

        } catch (IOException e) {
            e.printStackTrace();
        }

        JSONObject data = jsonObject.getJSONObject("data");
        String resUrl = data.getString("url");
        log.info("获取到图片连接,url为" + resUrl);

        return resUrl;

    }

    /**
     * 图片转义
     */
    private String encode(String url, String chartSet) {

        {
            try {
                Matcher matcher = Pattern.compile("[^\\x00-\\xff]").matcher(url);//双字节,包括中文和中文符号[^\x00-\xff]  中文[\u4e00-\u9fa5]
                while (matcher.find()) {
                    String tmp = matcher.group();
                    url = url.replaceAll(tmp, java.net.URLEncoder.encode(tmp, chartSet));
                }
            } catch (UnsupportedEncodingException e) {
                log.error("双字节编码异常：", e);
            }
            return url;
        }
    }
    /**
     * 运单凭证上传循环工具
     *
     * @param baseUrl
     * @param token
     * @return
     */
    private String shippingnoteForUtil(String baseUrl, String token,String companyId) {
        String[] urls;
        String upload = null;
        String upload1;
        if (baseUrl != null && baseUrl.contains(",")) {
            urls = baseUrl.split(",");
            for (int i = 0; i < urls.length; i++) {
                String a = urls[i];
                upload = upload(a, token, "2",companyId);
                upload1 = upload;
                upload = upload + "," + upload1;
            }
        } else {
            upload = upload(baseUrl, token, "2",companyId);
        }
        return upload;
    }

    /**
     * 获取列表
     * @param page
     * @param queryWrapper
     * @return
     */
    /**
     *
     * @param page
     * @param queryWrapper
     * @return
     */
    public IPage<YunFuTongShippingNoteDTO> getYunShuiBaoPageList(Page<YunFuTongShippingNoteDTO> page,
                                                                 QueryWrapper<YunFuTongShippingNoteDTO> queryWrapper) {
        IPage<YunFuTongShippingNoteDTO> pageList = hyShippingNoteMapper.getYunShuiBaoPageList(page, queryWrapper);
        return pageList;
    }

    /**
     * 运单轨迹上传
     */
    public Result<?> uploadTraces(HyShippingNote hyShippingNote, HyVehicle vehicle, String token,String companyId) {
        //业务数据
        YsbGuiji guiji = new YsbGuiji();
        if (hyShippingNote != null) {
            try {
                guiji.setCarriageBillID(hyShippingNote.getShippingNoteNumber());
                guiji.setTraceInfo(getRouterPath(vehicle,hyShippingNote));
                guiji.setCarNumber(vehicle.getVehicleNumber());
                guiji.setTraceStartTime(DateUtil.fomatString(hyShippingNote.getStatusDtLoading()));
                guiji.setTraceEndTime(DateUtil.fomatString(hyShippingNote.getStatusDtUnloading()));
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
            //请求数据
            HyCompanyEtcConfig companyEtcConfig = companyEtcConfigService.getOne(new QueryWrapper<HyCompanyEtcConfig>().eq("company_id", companyId).eq("report_type",1000));
            String addDriverUrl = companyEtcConfig.getEtcReportUrl()+"/api/v1/Waybill/UploadTrace";

          /*  //生成16位随机密钥
            String key = UUID.randomUUID().toString().replaceAll("-", "").substring(0, 16);
            byte[] keyByte = key.getBytes();
            log.info(key);*/
            //平台账号下对应公钥
            //  String pubk = "0404B2D01C149800E3961676191F9763D02347E6E2B490615D2FD83082F78C20220570F9AFE317D317E1DA9CF1DD5DF7BB4D750FC3DED2A20DD7775930569DF60D";
           // log.info("SM2加密输出 encryptCode: ");
           // String encryptCode = null;
            String result = null;
            JSONObject jsonObject = null;
           /* try {
                encryptCode = SM2Utils.encrypt(Util.hexToByte(pubk), keyByte);
                log.info(encryptCode);*/
                String encryptData = JSONUtil.toJsonStr(guiji);
                log.info("最终用postman提交的Json数据包");
                JSONObject postJson = new JSONObject();
                postJson.put("reqTime", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
                postJson.put("token", token);
                postJson.put("encryptCode", "");
                postJson.put("encryptData", encryptData);
                //log.info("最终postman提交的数据为" + postJson.toString());
                HttpEntity entity;
                // 实体类转换为Map
                Map<String, String> map2 = JSON.parseObject(JSON.toJSONString(postJson), Map.class);
                log.info("开始发送上传轨迹请求");
                entity = new StringEntity(JSONUtil.toJsonStr(map2), "utf-8");
                result = TestHttpClientUtil.httpPost(addDriverUrl, entity);
                log.info("上传轨迹返回结果++"+result.toString());
                jsonObject = JSONObject.parseObject(result);
                if (jsonObject.getString("code").equals("-1")) {
                    return Result.error(jsonObject.get("msg").toString());
                }
            /*} catch (IOException e) {
                e.printStackTrace();
            }*/

        }
        return Result.OK();




    }
    private String getRouterPath(HyVehicle vehicle, HyShippingNote hyShippingNote) throws Exception {

        //agl，正北方向夹角，（0--359 ，0正北）
        //gtm 接受时间
        List<Map<String,Object>> guijiList = new ArrayList<Map<String, Object>>();
        if (vehicle!=null){
            String startTime = DateUtils.dateTimeToString(hyShippingNote.getStatusDtLoading());
            String endTime = DateUtils.dateTimeToString(hyShippingNote.getStatusDtUnloading());
            Date startTimeDate = DateUtils.stringToDateTime(startTime);
            Date endTimeDate = DateUtils.stringToDateTime(endTime);
            WaybillRouteVO waybillRouteVO = new WaybillRouteVO();
            if (!endTimeDate.after(startTimeDate)) {
                throw new JeecgBootException("结束时间不能在开始时间之前！");
            }
            //如果开启了历史轨迹并且保存过轨迹，就调用已经保存的轨迹
            if (StrUtil.isNotEmpty(hyShippingNote.getShippingNoteNumber()) && HyCfgUtil.isUsed2("history_trace")) {
                //中交轨迹只能查询6个月的，超出6个月的可以尝试读取本地轨迹记录
                Integer second = DateUtils.getDifferentDaysByMillisecond(startTimeDate, new Date());
                if (second > (3600 * 24 * 180)) {
                    log.info("进入本地历史记录");
                    waybillRouteVO  = waybillRouteService.getWaybillByFile(hyShippingNote.getShippingNoteNumber());
                }else {
                    log.info("去请求中交");
                    waybillRouteVO = waybillRouteService.getRouterPath(vehicle.getVehicleNumber(), startTime, endTime, "");
                }
            }else {
                waybillRouteVO = waybillRouteService.getRouterPath(vehicle.getVehicleNumber(), startTime, endTime, "");
            }
            if (waybillRouteVO==null){
                throw new JeecgBootException(hyShippingNote.getShippingNoteNumber()+"轨迹不存在");
            }
            List<PointDataListVO> pointDataList = waybillRouteVO.getPointDataList();

            for (PointDataListVO pointDataListVO : pointDataList) {
                //时间,经度,维度,速度
                JSONObject json = new JSONObject();;
                json.put("gtm",pointDataListVO.getReceiveTime());
                json.put("lat",pointDataListVO.getLat());
                json.put("lon",pointDataListVO.getLng());
                json.put("spd",pointDataListVO.getCs());
                guijiList.add(json);
            }

        }
        return JSONObject.toJSONString(guijiList);
    }

    public void checkDriverInfo(HyDriver driver) {
        if (StringUtils.isEmpty(driver.getTelephone())) {
            throw new JeecgBootException("司机手机号不能为空");
        }
        if (StringUtils.isEmpty(driver.getIdcard())) {
            throw new JeecgBootException("司机身份证不能为空");
        }
        if (StringUtils.isEmpty(driver.getDriverName())) {
            throw new JeecgBootException("司机姓名不能为空");
        }
        if (StringUtils.isEmpty(driver.getVehicleClass())) {
            throw new JeecgBootException("司机准驾类型不能为空");
        }
        if (driver.getValidPeriodFrom()==null) {
            throw new JeecgBootException("司机驾驶证有效期不能为空");
        }
        if (driver.getValidPeriodTo()==null) {
            throw new JeecgBootException("司机驾驶证有效期不能为空");
        }
        if (StringUtils.isEmpty(driver.getDriverImg())) {
            throw new JeecgBootException("驾照正面照片不能为空");
        }
        if (StringUtils.isEmpty(driver.getDriverImg2())) {
            throw new JeecgBootException("驾照反面照片不能为空");
        }
    }

    public void checkVehicleInfo(HyVehicle vehicle) {
        if (StringUtils.isEmpty(vehicle.getVehicleNumber())) {
            throw new JeecgBootException("车牌号不能为空");
        }
        if (StringUtils.isEmpty(vehicle.getVehicleType())) {
            throw new JeecgBootException("车辆类型不能为空");
        }

        if (StringUtils.isEmpty(vehicle.getVehiclePlateColorCode())){
            throw new JeecgBootException("车辆颜色不能为空");
        }
        if (StringUtils.isEmpty(vehicle.getVehicleEnergyType())){
            throw new JeecgBootException("车辆能源类型不能为空");
        }
        if (StringUtils.isEmpty(vehicle.getOwner())){
            throw new JeecgBootException("车主不能为空");
        }
        if (vehicle.getVehicleTonnage()==null||vehicle.getVehicleTonnage().compareTo(BigDecimal.ZERO)<=0){
            throw new JeecgBootException("车辆载重不能为空");
        }
        if (vehicle.getGrossMass()==null||vehicle.getGrossMass().compareTo(BigDecimal.ZERO)<=0){
            throw new JeecgBootException("车辆吨位不能为空");
        }
        if (StringUtils.isEmpty(vehicle.getVehicleLong())){
            throw new JeecgBootException("车长不能为空");
        }
        if (StringUtils.isEmpty(vehicle.getVehicleEnergyType())){
            throw new JeecgBootException("车辆能源类型不能为空");
        }
        if (StringUtils.isEmpty(vehicle.getDrivingLicenseImg())){
            throw new JeecgBootException("车辆行驶证照片不能为空");
        }
        if (StringUtils.isEmpty(vehicle.getDrivingLicenseImg2())){
            throw new JeecgBootException("车辆行驶证照片不能为空");
        }
        if (StringUtils.isEmpty(vehicle.getRoadTransportImg())){
            throw new JeecgBootException("车辆道路运输证照片不能为空");
        }
    }
}